<template>
  <div class="upload-container" style="display: inline-block">
    <!--    <el-button icon='el-icon-upload' size="mini" :style="{background:color,borderColor:color}"-->
    <!--               @click=" dialogVisible=true" type="primary">上传图片-->
    <!--    </el-button>-->
    <span title="上传图片" @click="dialogVisible=true"><i class="el-icon-upload" style="font-size: 20px;" /> </span>
    <el-dialog :visible.sync="dialogVisible" width="90%" append-to-body title="上传图片" :close-on-click-modal="false" @close="uploadloading=false">
      <el-tabs v-model="activeName">
        <el-tab-pane label="上传图片" name="first">
          <el-row>
            <el-col :span="10">
              <div>
                <div style="margin-bottom: 10px; border: 1px solid #409EFF;padding: 5px">
                  <directory @handleClickNode="handleClickNode" />

                  <span v-if="selected_directory">当前选择目录: {{ selected_directory__name }}
                    <el-button size="mini" @click="() => selected_directory = null">取消指定目录</el-button>
                  </span>
                </div>
              </div>
            </el-col>
            <el-col :span="14">
              <el-input v-model="combin_search_keyword" placeholder="输入关键词方便后续搜索" />
              <el-tabs v-model="uploadType">
                <el-tab-pane label="本地上传" name="local">
                  <el-upload
                    :headers="headers"
                    class="editor-slide-upload"
                    :action="upload_url"
                    :multiple="true"
                    drag
                    :file-list="fileList"
                    :show-file-list="true"
                    :before-upload="beforeUpload"
                    :data="{ directory_id:selected_directory||-1, keyword: combin_search_keyword , project_id: this.$store.getters.projectId}"
                    list-type="picture-card"
                    :on-remove="handleRemove"
                    :on-success="handleSuccess"
                  >
                    <i class="el-icon-plus" />

                  </el-upload>
                  <el-alert
                    title="先选择目录,然后上传图片"
                    type="error"
                    :closable="false"
                  />
                </el-tab-pane>
                <el-tab-pane label="粘贴图片" value="paste">

                  <!-- 粘贴图片区域 -->
                  <div
                    class="paste-area"
                    contenteditable="true"
                    placeholder="在此处粘贴图片"
                    style="border: 1px dashed #ccc; padding: 10px; margin-bottom: 10px; min-height: 200px"
                    @paste="handlePaste"
                  >
                    在此处粘贴图片
                  </div>
                  <!-- 用户选择上传目标 -->
                  <el-button type="primary" :loading="uploadloading" @click="submitImage">提交图片</el-button>
                </el-tab-pane>
              </el-tabs>
              <ul v-if="success_urls.length != 0">
                <li v-for="(item,index) in success_urls" :key="index">{{ item }}</li>
              </ul>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="搜索图片" name="second">
          <el-row>
            <el-form ref="form" label-position="top" :model="image_search_form">
              <el-form-item label="keyword">
                <el-input v-model="image_search_form.keyword" placeholder="keyword" />
              </el-form-item>
              <el-form-item label="尺寸">
                <el-input v-model="image_search_form.width" style="width: 100px;" placeholder="width" />
                H:<el-input v-model="image_search_form.height" style="width: 100px;display: inline-block" placeholder="height" />
              </el-form-item>
            </el-form>
            <el-button type="success" :loading="image_search_loading" @click="handleImageSearch">搜索</el-button>
          </el-row>
          <el-row>
            <el-input v-model="image_search_result" type="textarea" />
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="合并图片" name="third">
          <el-row :gutter="10">
            <el-col :span="6">
              <div>
                <el-table
                  :data="this.combin_form.urls"
                  border
                  style="width: 100%"
                >
                  <el-table-column
                    label="img"
                  >
                    <template slot-scope="scope">
                      <a :href="scope.row.url" target="_blank"><img style="width: 50px; height: 50px" :src="scope.row.url"></a><br>
                      {{ scope.row.url.substring(0,100) }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    fixed="right"
                    label="操作"
                    width="120"
                  >
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        @click.native.prevent="deleteRow(scope.$index)"
                      >
                        移除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-row style="margin-top: 10px">
                  <el-col :span="12">
                    <el-button v-if="combin_form.urls.length > 0" size="mini" type="danger" @click="combin_form.urls=[]">清空选择</el-button>
                  </el-col>
                  <el-col :span="12">
                    <el-button v-if="combin_form.urls.length" style="text-align: right" type="primary" size="mini" :loading="createimageloading" @click="handleCreateImage">合并图片</el-button>
                  </el-col>
                </el-row>
                <el-row style="margin-top: 10px">
                  <span style="display: block;margin-bottom: 5px">图片生成结果:</span>
                  <span style="display: block">
                    <el-input v-if="new_image_url !== ''" v-model="new_image_url" class="input-with-select">
                      <el-button slot="append" @click="handleInsert()">插入</el-button>
                    </el-input>
                  </span>
                  <a v-if="new_image_url !== ''" target="_blank" :href="new_image_url"><el-image v-if="new_image_url !== ''" fit="fill" :src="new_image_url" style="width: 300px; height: 300px" /></a>
                </el-row>

              </div>
            </el-col>
            <el-col :span="18">
              <div>
                <el-image
                  v-for="(url,index) in images"
                  :key="index"
                  style="width: 100px; height: 100px"
                  :src="url"
                  fit="fill"
                  @dblclick="handleChoose"
                />
                <el-alert
                  title="双击图片选择要合并的图片,然后再左边表格下面点击合并按钮"
                  type="warning"
                />
              </div>

              <el-form ref="form" label-position="top" :model="combin_form" label-width="80px">
                <el-form-item label="尺寸">
                  <el-input v-model="combin_form.width" style="width: 100px;display: inline-block" placeholder="width" />X
                  <el-input v-model="combin_form.height" style="width: 100px;display: inline-block" placeholder="height" />
                </el-form-item>
                <el-form-item label="输入url每行一个">
                  <el-input v-model="combin_form.search_urls" type="textarea" :rows="5" placeholder="" @change="handleAdd" />
                </el-form-item>
                <el-input v-model="combin_search_keyword" placeholder="输入关键词搜索图片" class="input-with-select">
                  <el-button slot="append" icon="el-icon-search" :loading="combin_search_loading" @click="handleCombinSearchImage">搜索图片</el-button>
                  <el-button type="danger" @click="handleCleanCombinData">清空数据</el-button>
                </el-input>
              </el-form>

            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="修改尺寸" name="fourth">
          <el-row>
            <el-col :span="6">
              <div>
                <span>图片生成结果:</span>
                <a v-if="resize_image_url !== ''" target="_blank" :href="resize_image_url"><el-image v-if="resize_image_url !== ''" fit="fill" :src="resize_image_url" style="width: 300px; height: 300px" /></a>
              </div>
            </el-col>
            <el-col :span="18">
              <el-form ref="form" label-position="top" :model="resize_form">
                <el-form-item label="尺寸">
                  <el-select v-model="resize_form.t" placeholder="请选择" size="small" clearable>
                    <el-option label="等比例" value="all" />
                    <el-option label="按高度" value="baseheight" />
                    <el-option label="按宽度" value="basewidth" />
                  </el-select>
                  W:<el-input v-model="resize_form.width" style="width: 100px;display: inline-block" :disabled="resize_form.t == 'baseheight'" placeholder="width" />
                  H:<el-input v-model="resize_form.height" style="width: 100px;display: inline-block" :disabled="resize_form.t == 'basewidth'" placeholder="height" />
                  <el-upload
                    v-if="resize_form.height || resize_form.width"
                    :headers="headers"
                    :action="resize_url"
                    :multiple="false"
                    style="height: 100px"
                    drag
                    :data="resize_form"
                    :on-success="handleResizeSuccess"
                  >
                    <i class="el-icon-upload" />
                    <div class="el-upload__text">将文件拖到此处修改，或<em>点击上传</em><span style="color: red">(立即生效，请提前设置好尺寸)</span></div>
                  </el-upload>
                  <span style="display: block">-------</span>
                </el-form-item>

              </el-form>

            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
        <el-button v-if="activeName==='second'" type="primary" @click="handleSubmit">插 入</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { Image_Combination, Image_Search } from '@/api/eco/image'
import { Post as UploadBase64Image } from '@/api/cms/image'
import Directory from '../../views/cms/elements/directory'

export default {
  name: 'EditorImage',
  components: { Directory },
  props: {
    color: {
      type: String,
      default: '#1890ff'
    }
  },
  data() {
    return {
      image_search_form: {
        keyword: '',
        width: 1024,
        height: 1024,
        quantity: 100
      },
      image_search_result: '',
      image_search_loading: false,
      images: [],
      resize_image_url: '',
      resize_url: '',
      resize_form: {
        t: 'all',
        width: 0,
        height: 0
      },
      combin_form: {
        urls: [],
        width: 800,
        height: 800,
        search_urls: ''
      },
      combin_search_keyword: '',
      uploadType: 'local',
      uploadloading: false,
      combin_search_loading: false,
      new_image_url: '',
      createimageloading: false,
      success_data: [],
      activeName: 'first',
      dialogVisible: false,
      listObj: {},
      fileList: [],
      upload_url: '',
      success_urls: [],
      boolUploadSucceed: false,
      selected_directory: null,
      selected_directory__name: null
    }
  },
  computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  mounted() {
    this.boolUploadSucceed = false
    this.upload_url = process.env.VUE_APP_BASE_API + '/cms/api/image/'
    this.resize_url = process.env.VUE_APP_BASE_API + '/eco/api/image/image_resize/'
  },
  methods: {
    deleteRow(index) {
      console.log('delete ', index)
      const arr = []
      for (let i = 0; i < this.combin_form.urls.length; i++) {
        if (index !== i) {
          arr.push(this.combin_form.urls[i])
        }
      }
      this.combin_form.urls = arr
      // this.combin_form.urls = this.combin_form.urls.slice(index, 1)
    },
    handleChoose(v) {
      const url = v.toElement.currentSrc
      if (url) {
        let is_in = false
        for (let i = 0; i < this.combin_form.urls.length; i++) {
          if (this.combin_form.urls[i].url === url) {
            is_in = true
          }
        }
        if (!is_in) {
          this.combin_form.urls.push({ url: url })
        }
        console.log('add', v.toElement.currentSrc)
      }
    },
    handleCleanCombinData() {
      this.images = []
      this.combin_form = {
        urls: [],
        width: 800,
        height: 800,
        search_urls: ''
      }
      this.new_image_url = ''
    },
    handleCombinSearchImage() {
      this.combin_search_loading = true
      Image_Search({ keyword: this.combin_search_keyword, width: this.combin_form.width,
        height: this.combin_form.height, quantity: 100 }).then((response) => {
        this.combin_form.search_urls = response.urls.join('\n')
        this.images = this.combin_form.search_urls.trim().split('\n').filter(item => item.length > 0)
        this.combin_search_loading = false
      }).catch(err => {
        console.log(err)
        this.combin_search_loading = false
      })
    },
    handleImageSearch() {
      this.image_search_loading = true
      Image_Search(this.image_search_form).then((response) => {
        this.image_search_result = response.urls.join('\n')
        console.log(this.image_search_result, response.urls)
        this.image_search_loading = false
      }).catch(err => {
        console.log(err)
        this.image_search_loading = false
      })
    },
    handleResizeSuccess(response, file) {
      if (response.success) {
        this.$notify({
          title: '成功',
          message: `文件${file.name}上传成功`,
          type: 'success',
          duration: 1000
        })
        this.resize_image_url = response.url
      } else {
        this.$notify({
          title: '失败',
          message: `文件${file.name}上传失败, ${response.msg}`,
          type: 'error',
          duration: 3000
        })
      }
    },
    handleAdd(v) {
      this.images = this.combin_form.search_urls.trim().split('\n').filter(item => item.length > 0)
    },
    handleInsert() {
      // window.open(this.new_image_url, '_blank')
      const arr = []
      arr.push({ 'url': this.new_image_url, width: this.combin_form.width, height: this.combin_form.height })
      this.$emit('successCBK', arr)
      this.dialogVisible = false
    },
    handleCreateImage() {
      this.createimageloading = true
      Image_Combination({ keyword: this.combin_search_keyword, urls: this.combin_form.urls.map(item => item.url), width: this.combin_form.width, height: this.combin_form.height }).then((response) => {
        this.new_image_url = response.data['url']
        this.createimageloading = false
      }).catch(err => {
        console.log(err)
        this.createimageloading = false
      })
    },
    checkAllSuccess() {
      return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
    },
    submitImage() {
      if (!this.pastedImage) {
        this.$message.error('没有检测到粘贴的图片')
        return
      }
      if (this.uploadTarget === 'cloud') {
        // 上传到云服务器的逻辑...
      } else {
        this.uploadloading = true
        // 临时保存到本地的逻辑...
        UploadBase64Image({ file_data: this.pastedImage, directory_id: this.selected_directory || -1, keyword: this.combin_search_keyword }).then(response => {
          this.$message.success('图片已保存到本地')
          // 从url中提取文件
          this.success_data.push({ url: response.data.url, filename: response.data.filename })
          this.success_urls.push(response.data.url)
          this.handleInsertFile({ url: response.data.url, filename: response.data.filename })
          this.uploadloading = false
        }).catch(err => {
          console.log(err)
          this.uploadloading = false
        })
      }
    },
    handleInsertFile(item) {
      const arr = []
      arr.push({ 'url': item.url, width: 800, height: 800 })
      this.$emit('successCBK', arr)
    },
    handlePaste(event) {
      const items = (event.clipboardData || event.originalEvent.clipboardData).items
      for (const index in items) {
        const item = items[index]
        if (item.kind === 'file') {
          const blob = item.getAsFile()
          const reader = new FileReader()
          reader.onload = (e) => {
            this.pastedImage = e.target.result // base64编码的图片
          }
          reader.readAsDataURL(blob)
        }
      }
    },
    handleSubmit() {
      if (this.selected_directory === null) {
        alert('请选择目录')
        return
      }
      const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      if (!this.checkAllSuccess()) {
        this.$message('请等待所有图片上传成功 或 出现了网络问题，请刷新页面重新上传！')
        return
      }
      this.listObj = {}
      this.fileList = []
      this.success_urls = []
      this.dialogVisible = false
      this.boolUploadSucceed = false
      this.$emit('successCBK', arr)
    },
    handleSuccess(response, file) {
      if (response.success) {
        this.$notify({
          title: '成功',
          message: `文件${file.name}上传成功`,
          type: 'success',
          duration: 1000
        })
        const uid = file.uid
        const objKeyArr = Object.keys(this.listObj)
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            this.listObj[objKeyArr[i]].url = response.data.url
            this.success_urls.push(response.data.url)
            this.listObj[objKeyArr[i]].hasSuccess = true
            console.log('set success')
            return
          }
        }
      } else {
        this.$notify({
          title: '失败',
          message: `文件${file.name}上传失败, ${response.msg}`,
          type: 'error',
          duration: 3000
        })
      }
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },
    beforeUpload(file) {
      const _self = this
      const fileName = file.uid
      this.listObj[fileName] = {}
      return new Promise((resolve, reject) => {
        _self.listObj[fileName] = { hasSuccess: false, uid: file.uid }
        resolve(true)
      })
    },
    handleClickNode(data) {
      if (data.id !== -1) {
        this.selected_directory = data.id
        this.selected_directory__name = data.name
        this.combin_search_keyword = data.name
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
i:hover {
        color: red;
    }
svg:hover {
        color: red;
    }
  .editor-slide-upload {
    margin-bottom: 20px;
    :deep(.el-upload--picture-card) {
      width: 100%;
    }
  }
</style>
